import paho.mqtt.client as mqtt
from paho.mqtt.client import CallbackAPIVersion
import random
MQTT_BROKER = "127.0.0.1"
MQTT_PORT = 1883
MQTT_TOPIC_CONTROL = "iot/farm/control"
CLIENT_ID = f"control_publisher_{random.randint(0, 1000)}"

publisher_client = mqtt.Client(
    callback_api_version=CallbackAPIVersion.VERSION2,
    client_id=CLIENT_ID
)
publisher_client.connect(MQTT_BROKER, MQTT_PORT)

def send_control_command(device, command):
    try:
        payload = f"{device}:{command}"
        print(f"发送控制指令: {payload}")
        result = publisher_client.publish(MQTT_TOPIC_CONTROL, payload)
        if result.rc == 0:
            return {"status": "success", "payload": payload}
        else:
            return {"status": "failed", "error": f"发布失败 (code: {result.rc})"}
    except Exception as e:
        return {"status": "failed", "error": str(e)}